package j2se.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by jingqing.zhou on 2015/6/17.
 * 基于tcp协议的socket通信，实现用户登录
 * 服务器端
 */
public class server_bak {
    public static void main(String[] args) {
        //1.创建一个服务器端socket
        try {
            ServerSocket sst =  new ServerSocket(8999);
            System.out.println("服务器即将启动，等待客户端的链接=====>");
            Socket socket = sst.accept();//阻塞，等待客户端请求
            //3 获取输入流，并读取客户端信息
            InputStream is = socket.getInputStream();//字节输入流
            InputStreamReader isr = new InputStreamReader(is);//将字节流包装为字符流
            BufferedReader bufferedReader = new BufferedReader(isr);//为输入流添加缓冲

            String info = null ;
            //循环读取客户端信息
            while ((info = bufferedReader.readLine())!=null){
                System.out.printf("我是服务器，客户端说："+ info);
            }
            socket.shutdownInput();//关闭输入流

            //获取输出流，用于响应客户端请求
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流
            pw.write("欢迎您：admin！！");
            pw.flush();

            //关闭资源
            bufferedReader.close();
            pw.close();
            os.close();
            isr.close();
            is.close();
            socket.close();
            sst.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
